#include "server_sq.h"
#include "json_pack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

sqlite3 *create_database()
{
	sqlite3       *db;
	char          *zErrMsg = 0;
	int            rc;
	char           sql[1024];

        rc = sqlite3_open("server.db",&db);
        if(rc)
        {
                printf("Can not open database:%s\n",strerror(errno));
                return NULL;
        }

	memset(sql,0,sizeof(sql));
	sprintf(sql,"CREATE TABLE IF NOT EXISTS SERVER_TEMP("\
              "ID INTEGER PRIMARY KEY AUTOINCREMENT    NOT NULL,"\
              "SERVER_ID          CHAR(10)             NOT NULL,"\
              "TEMP               CHAR(10)             NOT NULL,"\
              "TIME               CHAR(50)             NOT NULL);");


	rc = sqlite3_exec(db,sql,NULL,0,&zErrMsg);
	if(rc != SQLITE_OK)
	{
		printf("SQL error:%s\n",zErrMsg);
		sqlite3_free(zErrMsg);
		return NULL;
	}
	printf("Table created successfully\n");
	return db;
}


//将p(编号-温度-日期)插入表table
int insert_temp(char *p,sqlite3 *db)
{
	char                   *zErrMsg = 0;
	char                    sql[100];
	struct client_data      str;
	int                     rc;
	char                    separator = '-';

	if(!p || !db)
	{
		return -1;
	}
	memset(&str,0,sizeof(str));
	//分割
	//if(split(p,&separator,&str) < 0)
	if(json_unpack(p,&str) < 0)
	{
		printf("unpack failure:%s\n",strerror(errno));
		return -2;
	}
	memset(sql,0,sizeof(sql)); 
	sprintf(sql,"INSERT INTO SERVER_TEMP (SERVER_ID,TEMP,TIME) VALUES('%s','%s','%s');",str.id,str.temp,str.time);

	//执行SQL语句
	rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg);
	if(rc != SQLITE_OK)
	{
		fprintf(stderr,"SQL error:%s\n",zErrMsg);
		sqlite3_free(zErrMsg);
		return -3;
	}
	//printf("Insert into table SERVER_TEMP successfully:%s\n",p);
      	return 0;
}


